package fun.codedesign.principle.deepjvm.classloader;

import java.io.IOException;
import java.io.InputStream;

public class ClassLoaderTest {

    public static void main(String[] args) {
        // 遵守双亲委派，重写findclass方法，否则重写loadClass方法
        // loadClass调用了findClass的方法，当parent及启动classloader都找不到时就从子classloader中去查找
        ClassLoader myLoad = new ClassLoader() {

            @Override
            protected Class<?> findClass(String name) throws ClassNotFoundException {
                Class<?> clazz = getClass(name);
                if (clazz != null) {
                    return clazz;
                }
                return super.findClass(name);
            }

            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
//                Class clazz = getClass(name);
//                if (clazz != null) {
//                    return clazz;
//                }
                return super.loadClass(name);
            }

            Class<?> getClass(String name) {
                String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                try {
                    InputStream is = getClass().getResourceAsStream(fileName);
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    return defineClass(name, b, 0, b.length);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        };

        try {
            Object obj = myLoad.loadClass("principle.deepjvm.classloader.ClassLoaderTest").newInstance();
            System.out.println(obj.getClass());
            // 这个obj使用的是自定义的classLoad 与 虚拟机自带的不是一个类加载器，所以返回false
            System.out.println(obj instanceof ClassLoaderTest);

        } catch (InstantiationException | IllegalAccessException
                |
                ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
